package com.project.api.common.filter;

import com.project.api.common.ApiResponse;
import com.project.api.common.auth.LoginToken;
import org.apache.http.impl.cookie.DefaultCookieSpecProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

public class Filter implements javax.servlet.Filter {
    @Autowired
//    private UserService userService;
    String[] includeUrls = new String[]{};

    @Override
    public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
        ServletContext context = filterConfig.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
//        userService =  ctx.getBean(UserService.class);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        //是否需要过滤
        boolean needFilter = isNeedFilter(uri);
        if (!needFilter) { //不需要过滤直接传给下一个过滤器
            filterChain.doFilter(servletRequest, servletResponse);
        } else { //需要过滤器
            String token = null;
            Enumeration<String> headerNames = request.getHeaderNames();
            while(headerNames.hasMoreElements()){
                String element = headerNames.nextElement();
                if (element.equalsIgnoreCase("access-control-request-headers")){
                    filterChain.doFilter(request, response);
                    return;
                }
//                System.out.println(element+":"+request.getHeader(element));
//                if (element.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) {
                if (element.equalsIgnoreCase("X-Token")) {
                    token=request.getHeader(element);
                    break;
                }
            }
//        response.setHeader("Access-Control-Allow-Credentials","true");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
//        response.addCookie(new Cookie("JSSESIONID",request.getSession().getId()));
        HttpSession session = request.getSession();
//        System.out.println("filter::"+session.getId());
//        String openid=(String)session.getAttribute("openid");
//        if(openid!=null) {
//            int userId = userService.create(openid);
//            session.setAttribute("userId",userId);
//        }


//            response.setHeader("Content-type", "application/json;charset=UTF-8");
//            response.setContentType("application/json;charset=UTF-8");
//            if (!LoginToken.Verify(session.getId(),token)) {
            if (!LoginToken.Verify((String) session.getAttribute(LoginToken.NAME),token)) {
                String requestType = request.getHeader("X-Requested-With");
                //判断是否是ajax请求（因为ajax页面不跳转，所以这块需要判断一下）
                if(requestType!=null && "XMLHttpRequest".equals(requestType)){
                    response.setHeader("Content-type", "application/json;charset=UTF-8");
                    request.getRequestDispatcher("/unlogin").forward(request, response);
//                    response.getWriter().write(ApiResponse.NOLOGIN());
                }else {
                    response.getWriter().write("还没有登录。");
                }
                return;
            }
            String newToken=LoginToken.reflesh((String) session.getAttribute(LoginToken.NAME));
            session.setAttribute(LoginToken.NAME,newToken);
            filterChain.doFilter(request, response);
            // session中包含user对象,则是登录状态
//            if(session!=null&&session.getAttribute("userId") != null){
//                // System.out.println("user:"+session.getAttribute("user"));
//                filterChain.doFilter(request, response);
//            }else{
//                String requestType = request.getHeader("X-Requested-With");
//                //判断是否是ajax请求（因为ajax页面不跳转，所以这块需要判断一下）
//                if(requestType!=null && "XMLHttpRequest".equals(requestType)){
//                    response.getWriter().write(ApiResponse.NOLOGIN());
//                }else{
//                    response.getWriter().write("还没有登录。");
////                    filterChain.doFilter(servletRequest, servletResponse);
//                    //重定向到登录页(需要在static文件夹下建立此html文件)
////                    response.sendRedirect(request.getContextPath()+"/login.html");
//                }
//                return;
//            }
        }
    }
    /**
     * @Description: 是否需要过滤
     */
    public boolean isNeedFilter(String uri) {
        for (String includeUrl : includeUrls) {
            if(includeUrl.equals(uri)) {
                return false;
            }
        }
        return true;

    }

    @Override
    public void destroy() {

    }
}
